package com.huang.we_chart.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
@CrossOrigin
public class UploadFile {



    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String fileupload(HttpServletRequest request, MultipartFile upload) throws IOException {

//        文件上传
        System.out.println("上传文件");

        //获取上传文件的名字
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //给上传的文件重新命名避免出现重名
        filename=uuid+"_"+filename;
        //要上传的位置
        String path = "D:/upload/";
        System.out.println(path);
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }

        upload.transferTo(new File(path,filename));
        String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/upload/"+filename;
        return url;

    }


}
